package com.obrempon.credit.market.ui.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonFragment
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponAuthStepSelfieFragmentBinding
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.ui.activity.ObremponAuthStepsAct
import com.obrempon.credit.market.ui.activity.ObremponCameraSelfieAct
import com.obrempon.credit.market.ui.dialog.ObremponSubmitSuccessDialog
import com.obrempon.credit.market.utils.ObremponImageUtil
import com.obrempon.credit.market.utils.log.ObremponLogger
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.io.File

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/22 13:40
 * @Annotation：认证流程 - 自拍照
 */
class ObremponAuthStepSelfieFragment(): CommonFragment(),EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks {
    lateinit var binding: ObremponAuthStepSelfieFragmentBinding
    private var stepItem: JSONObject? = null

    //是否选中删除信息,默认选中
    private var isSelectedDeleteInformation = true
    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun getObremponRootView(inflater: LayoutInflater): View {
        binding = ObremponAuthStepSelfieFragmentBinding.inflate(inflater)
        return binding.root
    }

    override fun initObremponView() {
        initObremponSelfieUploadCreditLimitApprovedTipsText()
        showObremponDeleteInformationTips()
        showObremponAuthStepSelfieBeforeView()
    }

    override fun initObremponListener() {
        //切换是否选中删除个人信息
        binding.deleteInformationTipsLayout.setOnClickListener {
            isSelectedDeleteInformation = !isSelectedDeleteInformation
            showObremponDeleteInformationTips()
        }
        binding.imgSelfieDefault.setOnClickListener {
            if (faceImgPath.isEmpty()){
                binding.buttonStartOrSubmit.callOnClick()
            }
        }
        binding.imgSelie.setOnClickListener {
            binding.buttonStartOrSubmit.callOnClick()
        }
        //删除照片
        binding.imgRemove.setOnClickListener {
            if (faceImgPath.isNotEmpty()){
                addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_SELFIE_REMOVE_PHOTO,faceImgUrl)
                //删除图片
                val imgFile = File(faceImgPath)
                if (imgFile.isFile){
                    imgFile.delete()
                }
            }
            faceImgPath = ""
            faceImgUrl = ""
            showObremponAuthStepSelfieBeforeView()
        }
        //提交
        binding.buttonStartOrSubmit.setOnClickListener {
            //开始人脸拍照
            if (faceImgUrl.isEmpty()){
                if (EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)){
                    openObremponAuthStepSelfieCamera()
                } else {
                    EasyPermissions.requestPermissions(this, getString(R.string.obrempon_auth_step_selfie_camera_reason),1001,Manifest.permission.CAMERA)
                }
                return@setOnClickListener
            }
            //提交
            val params = JSONObject().addCommonParams().apply {
                put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_OCR_INFO_PATH)
                put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE、NONE）
                put("faceImgUrl",faceImgUrl)//人脸图片
            }
            ObremponLogger.e(">>>>>>>selfie>>>>>>params ：$params")

            //选中删除信息提示
            if (isSelectedDeleteInformation){
                showObremponDeleteInformationTipsDialog()
                launch(Dispatchers.Main){
                    delay(1500)
                    submitObremponSelfieDataAction(params)
                }
            } else {
                submitObremponSelfieDataAction(params)
            }
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_SELFIE_CONFIRM_SUBMIT)
        }
    }

    override fun takeObremponData() {
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_SELFIE_START)
    }

    private fun initObremponSelfieUploadCreditLimitApprovedTipsText(){
        val showApprovedKey1 = getString(R.string.obrempon_auth_step_ocr_upload_credit_limit_approved_tips_key1)
        val showApprovedKey2 = getString(R.string.obrempon_auth_step_ocr_upload_credit_limit_approved_tips_key2)
        val showApprovedText = String.format(getString(R.string.obrempon_auth_step_ocr_upload_credit_limit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff5811)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff5811)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textSelfieUploadCreditLimitApprovedTips.text = approvedTipsSpannable
    }

    private fun showObremponDeleteInformationTips(){
        when(isSelectedDeleteInformation){
            true -> {
                binding.imgSelectDeleteInformation.setImageResource(R.mipmap.obrempon_auth_step_ocr_delete_information_selected_icon)
            }
            else -> {
                binding.imgSelectDeleteInformation.setImageResource(R.mipmap.obrempon_auth_step_ocr_delete_information_normal_icon)
            }
        }
    }

    /**
     * 人脸拍照
     */
    private val selfieCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                ObremponLogger.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                showObremponAuthStepSelfieAfterView(imgLocalPath,imgUrl)
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showObremponAuthStepSelfieBeforeView(){
        binding.imgSelfieDefault.visibility = View.VISIBLE
        binding.selfieImgLayout.visibility = View.GONE
        binding.buttonStartOrSubmit.text = getString(R.string.obrempon_button_take_selfie).uppercase()
    }

    /**
     * 显示拍照之后的View
     */
    private fun showObremponAuthStepSelfieAfterView(imgPath: String, imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        ObremponImageUtil.instance.loadImageUrl(requireContext(),binding.imgSelie,faceImgPath)
        binding.imgSelfieDefault.visibility = View.GONE
        binding.selfieImgLayout.visibility = View.VISIBLE
        binding.buttonStartOrSubmit.text = getString(R.string.obrempon_button_confirm_submit).uppercase()
        val eventRemark = "FACE Url $$$imgUrl"
        addEventPointRequestAction(ObremponEventPointType.FORM.OBREMPON_FORM_STEP_SELFIE_UPLOAD_URL,eventRemark)
    }

    /**
     * 打开相机
     */
    private fun openObremponAuthStepSelfieCamera(){
        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_STEP_SELFIE_START_TAKE)
        selfieCameraResultLauncher.launch(Intent(context, ObremponCameraSelfieAct::class.java))
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_AGREE, it)
        }
        if (requestCode == 1001){
            openObremponAuthStepSelfieCamera()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_DENY, it)
        }
        // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            // 设置 引导用户前往设置界面 自行设置权限的引导对话框
            AppSettingsDialog.Builder(this)
//                .setTitle("需要手动设置权限")
//                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
//                .setPositiveButton("前往设置界面")
//                .setNegativeButton("不使用该功能")
                .build().show()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        ObremponLogger.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        ObremponLogger.e("onRationaleDenied, code: $requestCode")
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1001){
            // 判断五种权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)
            if (hasPermissions){
                openObremponAuthStepSelfieCamera()
            }
        }
    }

    /**
     * 提交成功提示
     */
    private fun showObremponDeleteInformationTipsDialog(){
        val sendSuccessDialog = ObremponSubmitSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(true)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.setTipsSuccessText(getString(R.string.obrempon_auth_step_ocr_submit_success_tips))
        launch(Dispatchers.Main){
            delay(1500)
            sendSuccessDialog.dismiss()
        }
    }

    /**
     * 提交
     */
    private fun submitObremponSelfieDataAction(params: JSONObject){
        val act = getAct() as ObremponAuthStepsAct
        act.onObremponAuthStepSubmitAction(params)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_STEP_SELFIE_END)
    }
}